// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

pub mod signal;
pub mod utils;

use tauri::{LogicalPosition, Manager, Position, Window, WindowEvent};
use tauri::{SystemTray, CustomMenuItem, SystemTrayMenu, SystemTrayMenuItem, SystemTrayEvent};
use signal::computer::*;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex,
};

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

fn main() {
    // 这里 `"quit".to_string()` 定义菜单项 ID，第二个参数是菜单项标签。
    let hide = CustomMenuItem::new("hide".to_string(), "隐藏");
    let quit = CustomMenuItem::new("quit".to_string(), "退出");

    let tray_menu = SystemTrayMenu::new()
    .add_item(hide)
    .add_native_item(SystemTrayMenuItem::Separator)
    .add_item(quit);

    let system_tray = SystemTray::new().with_menu(tray_menu);

    let should_stop = Arc::new(AtomicBool::new(false));
    tauri::Builder::default()
        .manage(AppSate {
            should_stop: should_stop.clone(),
        })
        .setup(|app| {
            println!("tauri setup");
            let main_window = app.get_window("main").unwrap();
            //main_window.maximize().expect("failed to maximize window");
            main_window.listen("stop-task", move|event|{
               println!("got event name whith payload {:?}", event.payload());
               should_stop.store(true, Ordering::Relaxed); 
            });


            let window_size = main_window.inner_size().unwrap();
            println!("窗口大小 {:?}", window_size);

            let monitor_option = main_window.current_monitor().unwrap();

            if let Some(monitor) = monitor_option {
                println!("显示器屏幕尺寸： {:?}", monitor.size());

                let windows_position = Position::Logical(
                  LogicalPosition::new(
                  monitor.size().width as f64 - window_size.width as f64,
                  (monitor.size().height as f64 - window_size.height as f64)/2.0)
                );
                main_window.set_position(windows_position).unwrap();
            }


            println!("tauri setup end");
            Ok(())
        })
        .system_tray(system_tray)
        .on_system_tray_event(|app, event| menu_handle(app, event))
        .invoke_handler(tauri::generate_handler![greet, init_process, collet_cpu])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

fn menu_handle(app_handle: &tauri::AppHandle, event: SystemTrayEvent) {
    match event {
      SystemTrayEvent::LeftClick {
        position: _,
        size: _,
        ..
      } => {
        println!("鼠标-左击");
      }
      SystemTrayEvent::RightClick {
        position: _,
        size: _,
        ..
      } => {
        println!("鼠标-右击");
      }
      SystemTrayEvent::DoubleClick {
        position: _,
        size: _,
        ..
      } => {
        println!("鼠标-双击");
      }
      SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
        "quit" => {
          std::process::exit(0);
        }
        "hide" => {
          let item_handle = app_handle.tray_handle().get_item(&id);
          let window = app_handle.get_window("main").unwrap();
          if window.is_visible().unwrap() {
            window.hide().unwrap();
            item_handle.set_title("显示").unwrap();
          } else {
            window.show().unwrap();
            item_handle.set_title("隐藏").unwrap();
          }
        }
        _ => {}
      },
      _ => {}
    }
  }
